import { logout } from '@w/apis/user'
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'

import storage from '~utils/storage'
import { PREFIX } from '~utils/util'

const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: {}
  }),
  getters: {
    token: (state) => state.userInfo?.token
  },
  actions: {
    setUserInfo(userInfo) {
      this.userInfo = {
        ...this.userInfo,
        ...userInfo
      }
    },
    async userLogout(router) {
      try {
        await logout()
        this.userInfo = {}
        ElMessage.success('退出成功')
      } catch (error) {
        console.error('Logout error:', error)
        ElMessage.error('退出失败')
      } finally {
        storage.clear()

        if (router) {
          router.push('/login')
        } else {
          // window.location.href = '/login'
          ElMessage.error('跳转登录页失败，请手动刷新')

        }
      }
    }
  },
  persist: {
    key: `${PREFIX}|userInfo`,
    storage: window.sessionStorage,
    paths: ['userInfo']
  }
})

export default useUserStore
